<?php


namespace App\Models\Admin;


use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Log\UserLog;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{

    const OPERATE_PID = 1;
    const MODEL       = 'users';

    use AdminTrait;

    protected $table      = 'users';
    protected $guarded    = [];
    protected $dateFormat = 'U';
    protected $hidden     = [
        'password', 'remember_token',
    ];

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return ['role' => 'admin'];
    }

    public function msgLast()
    {
        return $this->hasOne(CustomerMsg::class, 'user_id', 'id')->orderBy('created_at', 'desc');
    }

    public function role()
    {
        return $this->belongsTo(AdminRole::class, 'role_id', 'id');
    }

    public function setting()
    {
        return $this->belongsTo(Setting::class, 'company_id', 'id');
    }

    public static function getList($where)
    {
        $list = self::getwhere($where)
            ->with([
                'role:id,name'
            ])
            ->get();
        return $list;
    }

    public static function getListCust($where)
    {
        $list = self::getwhere($where)
            ->with([
                'setting:id,site_logo',
                'msgLast:user_id,msg,msg_type,created_at',
            ])
            ->select('id', 'name', 'company_id')
            ->get();
        return $list;
    }

    public static function getWhere($where)
    {
        $select = self::where([]);
        if (!empty($where['company_id']))
            $select = $select->where('company_id', $where['company_id']);
        if (!empty($where['role_id']))
            $select = $select->where('role_id', $where['role_id']);
        if (isset($where['company_ids'])) {
            $user_ids_arr = self::whereIn('company_id', $where['company_ids'])->pluck('id');
            $select       = $select->whereIn('id', $user_ids_arr);
        }
        return $select;
    }

    public static function addLog($pre, $next, $type, $method = '')
    {
        $info = AdminOperateModule::where('pid', self::OPERATE_PID)->where('type', $type)->where('model', self::MODEL)->when($method, function ($query) use ($method) {
            $query->where('method', $method);
        })->first();
        if (!empty($info)) {
            $adminLog = new UserLog($pre, $next, $info);
            $adminLog->addLog();
        }
    }
}
